<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['categoryTag:categoryTag:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['categoryTag:categoryTag:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['categoryTag:categoryTag:export']"
        >导出</el-button>
      </el-col>-->
      <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="filteredCategoryTagList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="80">
        <template
          #default="scope"
        >{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="labelName" width="150" />
      <!-- 颜色列 -->
      <el-table-column label="颜色" align="center" prop="color" width="80">
        <template #default="scope">
          <div class="color-cell">
            <div
              :style="{ 
            width: '18px', 
            height: '18px', 
            border: '1px solid #dcdfe6',
            backgroundColor: scope.row.color, 
            display: 'inline-block'
          }"
            ></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" show-overflow-tooltip />
      <!-- 效果列 -->
      <el-table-column label="效果" align="center" width="150">
        <template #default="scope">
          <el-tag
            :style="{
              backgroundColor:lightenColor(scope.row.color,0.1), 
              color:scope.row.color, 
              borderColor:lightenColor(scope.row.color,0.3),
              padding: '4px 10px',}"
            effect="light"
            round
          >{{ scope.row.labelName.slice(0, 6) }}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['categoryTag:categoryTag:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['categoryTag:categoryTag:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->

      <el-table-column align="right" width="200px">
        <template #header>
          <el-input v-model="search" size="default" placeholder="请输入标签或描述" />
        </template>
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['categoryTag:categoryTag:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['categoryTag:categoryTag:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分类标签对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="categoryTagRef" :model="form" :rules="rules" label-width="75px">
        <el-form-item label="标签" prop="labelName">
          <el-input v-model="form.labelName" placeholder="请输入标签名" style="width: 350px;" />
        </el-form-item>
        <!-- 颜色选择器 -->
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="form.color" :predefine="predefineColors"></el-color-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
            style="width: 350px;"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CategoryTag" >
import {
  listCategoryTag,
  getCategoryTag,
  delCategoryTag,
  addCategoryTag,
  updateCategoryTag
} from "@/api/categoryTag/categoryTag";
import { color } from "echarts";
import { radioGroupEmits } from "element-plus";

const { proxy } = getCurrentInstance();

const categoryTagList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const predefineColors = ref([
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585"
]);

// 搜索词
const search = ref("");

// 计算属性：基于搜索词过滤列表
const filteredCategoryTagList = computed(() => {
  if (!search.value) return categoryTagList.value; // 如果没有搜索词，则返回原始列表

  const searchLower = search.value.toLowerCase();

  // 过滤逻辑，确保 item.labelName 和 item.description 存在且为字符串
  return categoryTagList.value.filter(
    item =>
      (item.labelName &&
        typeof item.labelName === "string" &&
        item.labelName.toLowerCase().includes(searchLower)) ||
      (item.description &&
        typeof item.description === "string" &&
        item.description.toLowerCase().includes(searchLower))
  );
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    labelName: null,
    description: null,
    color: null
  },
  rules: {
    labelName: [{ required: true, message: "标签名不能为空", trigger: "blur" }],
    color: [{ required: true, message: "颜色不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询分类标签列表 */
function getList() {
  loading.value = true;
  listCategoryTag(queryParams.value).then(response => {
    categoryTagList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    labelName: null,
    description: null,
    color: null,
    userId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("categoryTagRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分类标签";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getCategoryTag(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分类标签";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["categoryTagRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCategoryTag(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategoryTag(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除分类标签编号为"' + _ids + '"的数据项？')
    .then(function() {
      return delCategoryTag(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "categoryTag/categoryTag/export",
    {
      ...queryParams.value
    },
    `categoryTag_${new Date().getTime()}.xlsx`
  );
}

// 增加透明度
function lightenColor(hex, alpha) {
  const rgb = hexToRgb(hex);
  if (rgb) {
    return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
  }
  return hex;
}

// 工具函数 hexToRgb
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      }
    : null;
}

getList();
</script>

<style scoped>
.color-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
